#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import glob
import optparse
import os
import os.path
import shutil
import subprocess
import sys
import tempfile
import j264_utils

#~ Process one directory for VDR files.
def processVdrDir( videoFiles, sourceIniFile, outputDir ):
    for rootDir in videoFiles.keys():
        #~ pushd inputDir.
        curDir = os.getcwd()
        os.chdir( rootDir )

        #~ Make output directory.
        dirParts = rootDir.split( os.sep )[-2:]
        outputDir = os.path.abspath( outputDir ) + os.sep + os.sep.join( dirParts )
        if not os.path.exists( outputDir ):
            os.makedirs( outputDir )

        #~ Make a temp file for ProjectX's cfg.
        iniFileObject = tempfile.NamedTemporaryFile( prefix = "j264-" )
        iniFileObject.close()
        iniFile = iniFileObject.name

        #~ Copy the user provided file into the temp file.
        shutil.copyfile( sourceIniFile, iniFile )

        #~ Set the output directory in the ini file.
        iniFileObject = open( iniFile, "a+" )
        print( "Application.OutputDirectory=%s\n" % outputDir, file = iniFileObject )
        iniFileObject.close()

        #~ Run ProjectX with correct locale.
        vdrFiles = sorted( videoFiles[rootDir] )
        pxCmd = "LANG=fi_FI java -Djava.awt.headless=true -jar ~/tools/projectx/projectx.jar -ini \"%s\" \"%s\"" % ( iniFile, "\" \"".join( vdrFiles ) )
        # print( pxCmd )
        p = subprocess.Popen( pxCmd, shell = True )
        os.waitpid( p.pid, 0 )

        #~ Postprocess output directory for subtitles (.idx/.sub).
        j264_utils.postprocessSubtitles( outputDir )

        #~ Copy info.vdr from source directory to target directory.
        infoCopied = False
        try:
            shutil.copyfile( rootDir + "/info.vdr", outputDir + "/info.vdr" )
            infoCopied = True
        except:
            pass
        if not infoCopied:
            try:
                shutil.copyfile( rootDir + "/info", outputDir + "/info" )
            except:
                print( ">>>VDR's recording info file not found." );

        #~ popd.
        os.chdir( curDir )

#~ 'Main'
if __name__ == "__main__":
    #~ Handle options.
    usageString = "%prog -o OUTDIR [-i PROJETX_INI_PREP] input-directories"
    parser = optparse.OptionParser( usage = usageString )
    parser.add_option( "-i", "--ini-file", dest = "ini",
                      help = "[optional] use FILE as ProjectX's ini-file", metavar = "FILE" )
    parser.add_option( "-o", "--output-directory", dest = "outdir",
                      help = "use DIR as output directory", metavar = "DIR" )
    ( options, args ) = parser.parse_args()
    #~ Sanity checking.
    if options.ini is None:
        # If ini file is not specified, try the script's home.
        scriptHome = os.path.split( os.path.abspath( sys.argv[0] ) )[0]
        prepFiles = glob.glob( scriptHome + os.sep + "*.prep" )
        try:
            options.ini = prepFiles.pop( 0 )
        except:
            print( ">>>Ini-file was not specified nor was such automagically found from the tool home directory!", file = sys.stderr )
            parser.parse_args( ["-h"] )
    if options.outdir is None:
        print( ">>>Output directory was not specified!", file = sys.stderr )
        parser.parse_args( ["-h"] )
    if not len( args ):
        print( ">>>No input directories specified", file = sys.stderr )
        parser.parse_args( ["-h"] )

    # Process input directories.
    for inputDir in args:
        if os.path.isfile( inputDir ):
            dirPart, filePart = os.path.split( inputDir )
            processVdrDir( {dirPart:filePart}, options.ini, os.path.abspath( options.outdir ) )
        else:
            j264_utils.processInputDir( os.path.abspath( inputDir ), "\d+\.vdr|mod|ts", processVdrDir, options.ini, os.path.abspath( options.outdir ) )
